using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcContrib;
using DecisionMaking.BusinessLogic;
using DecisionMaking.BusinessLogic.Model;

namespace DecisionMaking.WebApp
{
	/// <summary>
	/// Responsible for Environment management operations
	/// </summary>
	[HandleError]	
	public class EnvironmentsController : BaseController
	{
		/// <summary>
		/// Injected by Windsor 
		/// </summary>
		public IEnvironmentManager EnvironmentManager {private get; set;}

		[HttpGet]
		public ActionResult Index() // environment list
		{
			ViewData["environments"] = EnvironmentManager.GetEnvironments(CurrentAccount.Id);
			return View("List");
		}
		
		[HttpGet]
		public ActionResult Add()
		{
			return View("Edit");
		}
		
		[HttpPost]
		public ActionResult Add(EnvironmentModel model)
		{
			try
			{
				model.AccountId = CurrentAccount.Id;
				var environment = EnvironmentManager.SaveEnvironment(model);
				// go to edit cue attributes
				return this.RedirectToAction<CueAttributesController>(c => c.List(environment.Id));				
			}
			catch (DuplicateEnvironmentNameException e)
			{
				ModelState.AddModelError("Name", "An environment with this name already exists");
				
			}
			
			return View("Edit", model);

		}		
		
		[HttpGet]
		public ActionResult Edit(int id)
		{
			try
			{
				var environment = EnvironmentManager.GetEnvironment(id);
				
				if (environment.Account.Id == CurrentAccount.Id)
				{
					var model = new EnvironmentModel
					{
						Id = environment.Id,
						Name = environment.Name,
						Description = environment.Description,
						IndependentVariable = environment.IndependentVariableName,
						IsPublic = environment.Settings.IsPublic
					};
					
					return View(model);
				}
				else
				{
					return AccessDenied();
				}
			} 
			catch (EntityNotFoundException e)
			{
				return NotFound(e);
			}
		}	
		
		[HttpPost]
		public ActionResult Edit(EnvironmentModel model)
		{
			try
			{
				model.AccountId = CurrentAccount.Id;
				var environment = EnvironmentManager.SaveEnvironment(model);
				// go to edit cue attributes
				return this.RedirectToAction(c => c.Index());				
			}
			catch (DuplicateEnvironmentNameException e)
			{
				ModelState.AddModelError("Name", "An environment with this name already exists");
				
			}
			catch (AccessDeniedException e)
			{
				return AccessDenied(e);
			}
			catch (EntityNotFoundException e)
			{
				return NotFound(e);
			}
			
			return View(model);
		}	
	
		
	}
}

